﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;
using System.Runtime.InteropServices;

namespace FireZone
{
    internal static class ObservableCollectionExtension
    {
        public static void AddAsync<T>(this ObservableCollection<T> collection, T item)
        {
            if(Application.Current.Dispatcher.CheckAccess())
            {
                collection.Add(item);
            }
            else
            {
                Application.Current.Dispatcher.Invoke(new Action<ObservableCollection<T>, T>(AddAsync), collection, item);
            }
        }

        public static bool RemoveAsync<T>(this ObservableCollection<T> collection, T item)
        {
            if (Application.Current.Dispatcher.CheckAccess())
            {
                return collection.Remove(item);
            }
            else
            {
                return (bool)Application.Current.Dispatcher.Invoke(new Func<ObservableCollection<T>, T, bool>(RemoveAsync), collection, item);
            }
        }

        public static bool AddOrUpdateAsync<T>(this ObservableCollection<T> collection, T item)
        {
            if(Application.Current.Dispatcher.CheckAccess())
            {
                int index = collection.IndexOf(item);
                if(index <0)
                {
                    collection.Add(item);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return (bool)Application.Current.Dispatcher.Invoke(new Func<ObservableCollection<T>, T, bool>(AddOrUpdateAsync), collection, item);
            }
        }
    }
}
